define(["jquery", "jqueryui", "util/formSetting", "util/formRender", 'util/commonUtil', "util/formElementManager"], 
	function($, jqueryui, formSetting, formRender, commonUtil, formElementManager) {
	
	//布局拖拽结束后的处理函数
	let layoutWrapperDragOver = (helper) => {
		$("#layout-main .ui-draggable.active").removeClass("active");
		helper.removeClass("content-column-helper").addClass("formdesigner-v2021 content-column active").removeAttr("style");
		helper.empty();
		
		//let _btnMove = '<span class="label-btn drag label label-default"><i class="glyphicon glyphicon-move"></i>拖动</span>';
		//let _btnRemove = '<span class="label-btn remove label label-danger"><i class="glyphicon-remove glyphicon"></i>删除</span>';
		let _titleDiv = '<div class="drag-form-title"><span contenteditable="false" class="laytitle">标题</span></div>';
		let _contentDiv = '<div class="drag-form-lay"></div>';
		helper.append(_titleDiv);
		helper.append(_contentDiv);
		formRender.renderLayoutWrapper(helper);
		formSetting.renderLayoutSettingPanel();
	}

	//表单控件拖拽结束后的处理函数
	let layoutElementDragOver = (helper) => {
		// 开发组件相关后在此调用组件渲染方法
		if(!helper.closest("#drag-workarea").length) {
			return;
		}
		$("#layout-main .ui-draggable.active").removeClass("active");
		helper.removeClass("content-column-helper").addClass("formdesigner-v2021 draggable-element active").removeAttr("style");
		/*let _btnMove = '<span class="label-btn drag label label-default"><i class="glyphicon glyphicon-move"></i>拖动</span>';
		let _btnRemove = '<span class="label-btn remove label label-danger"><i class="glyphicon-remove glyphicon"></i>删除</span>';
		let _titleDiv = '<div class="drag-form-title"><span contenteditable="true" class="laytitle">标题</span></div>';
		let _contentDiv = '<div class="drag-form-lay"></div>';
		helper.empty().append(_btnMove).append(_btnRemove);
		helper.append(_titleDiv);
		helper.append(_contentDiv);*/
		helper.empty();
		
		let tmpInstance;
		let componentName = helper.attr('data-conp-name');
		if( componentName ) {
			// 拖拽元素必定生成新的对象实例
			tmpInstance = new window[componentName]();
			helper.data("componentInstance", tmpInstance);
		}
		
		formRender.renderLayoutElement(helper);
		
		if(typeof tmpInstance === 'object') {
			//helper.attr("data-dom-id", tmpInstance.id);
			helper.append(tmpInstance.createDom());
			let property = tmpInstance.property;
			if(property) {
				let isViewPage = (pageKind ?? "") === "view";
				tmpInstance.label(property.propertyName);
				tmpInstance.required(!isViewPage && property.isRequiredField == "1");
				tmpInstance.forceReadonly(isViewPage || property.readonly);
			}
			tmpInstance.updateWidth(helper.closest(".content-column").attr("data-laywidth-inner"));
		}
		formRender.render(helper);
		formSetting.renderPanel();
	}
	
	/**
	 * 表单预览
	 */
	let formView = () => {
		commonUtil.modal.toast("开发中...");
	}
	
	/**
	 * 表单保存
	 */
	let formSave = () => {
		console.log(APP_CONFIG);
		/**
		 * 需要提交的参数
		 * modelType
		 * modelId
		 * id
		 * layoutElement #页面上显示的属性的属性编码列表
		 * echoElement #这个字段，在旧版本上保存在txt文件中，没什么用
		 * htmlCode #页面上拖拽生成的html
		 */
		//检测全局参数
		if(!modelType) { alert('参数modelType错误'); return; }
		if(!modelId) { alert('参数modelId错误'); return; }
		if(!pageId) { alert('参数id错误'); return; }
		if(!pageType) { alert('参数pageType错误'); return; }
		
		let layoutElement, echoElement = '', htmlCode;
		
		let workspace = $("#layout-main");
		{
			//将全局配置写入提交表单
			let pageConfigParam = $("#page-config-param");
			if(!pageConfigParam.length) {
				pageConfigParam = $('<div id="page-config-param" style="display:none;"></div>');
				workspace.prepend(pageConfigParam);
			}
			pageConfigParam.text(JSON.stringify(formSetting.formConfig.getConfig()));
		}
		
		{
			//获取 layoutElement #页面上显示的属性的属性编码列表
			let arr = [];
			workspace.find('[name]').each(function(){
				arr.push($(this).attr("name"));
			});
			console.log(arr);
			if(arr.length) {
				layoutElement = arr.join(",");
			} else {
				layoutElement = '';
			}
		}
		
		{
			//页面html
			let ghost = $(workspace.html());
			let div = $('<div></div>');
			ghost.appendTo(div);
			div.find(".btn-wrapper").remove();
			div.find(".content-column.active").removeClass("active");
			div.find(".draggable-element.active").removeClass("active");
			
			htmlCode = div.html();
			echoElement = htmlCode; // TODO  ！！！ 将echoElement设置为htmlCode纯属为了兼容之前的后台接口，后期优化接口后，这里可以删除
		}
		
		let param = {
			"id": pageId,
			"modelType": modelType,
			"modelId": modelId,
			//"pageType": pageType,
			"layoutElement": layoutElement,
			"echoElement": echoElement,
			"htmlCode": htmlCode
		}
		
		let url = APP_CONFIG.domain.cmdb + "/modelPage/htmlSave";
		commonUtil.mask();
		$.ajax({
			"url": url,
			"data": param,
			"type": "post",
			"dataType": "json",
			"success": function(data) {
				console.log(data);
				if(data?.message == 1) {
					commonUtil.info("保存成功");
				} else {
					commonUtil.error("保存失败");
				}
			},
			"complete": function() {
				console.log("complete");
				commonUtil.unmask();
			}
		});
		//$.ajax();
	}
	
	/**
	 * 表单全部设为只读
	 */
	let formSetReadonly = () => {
		
	}
	
	/**
	 * 表单全部取消只读
	 */
	let formCancelReadonly = () => {
		
	}
	
	/**
	 * 表单设置
	 */
	let formConfig = () => {
		formSetting.formConfig.render();
	}
	
	
	/**
	 * 清空工作区
	 */
	let formEmptyWorkspace = () => {
		
	}
	
	
	
	let _initCommon = () => {
		{
			//事件
			$(document).on("click", "#layout-left .toggle-next", function(evt) {
				//左侧折叠面板展开折叠
				$(this).next().toggle();
			}).on("click", ".event-wrap .edit", function(evt) {
				//修改自定义事件
				let wrap = $(this).closest('.event-wrap');
				let eventName = wrap.attr("data-eventName");
				let tmpInstance = wrap.data('connectDomIns');
				if(tmpInstance) {
					let eventContent = tmpInstance.events()[eventName];
					formSetting.formEvent.editEvent(eventName, eventContent, tmpInstance);
				}
			}).on("click", ".event-wrap .remove", function(evt) {
				//删除自定义事件
				let wrap = $(this).closest('.event-wrap');
				let eventName = wrap.attr("data-eventName");
				let tmpInstance = wrap.data('connectDomIns');
				if(tmpInstance) {
					formSetting.formEvent.removeEvent(eventName, tmpInstance);
				}
			}).on("click", ".header-menu .btn-view", function(evt) {
				//预览
				formView();
			}).on("click", ".header-menu .btn-save", function(evt) {
				//保存
				formSave();
			}).on("click", ".header-menu .btn-readonly-y", function(evt) {
				//只读
				formSetReadonly();
			}).on("click", ".header-menu .btn-readonly-n", function(evt) {
				//取消只读
				formCancelReadonly();
			}).on("click", ".header-menu .btn-config", function(evt) {
				//设置
				formConfig();
			}).on("click", ".header-menu .btn-empty", function(evt) {
				//清空
				formEmptyWorkspace();
			});
			
			//事件
			$("#layout-main").on("click", ".remove-content-column", function(evt) {
				//删除布局
				evt.stopPropagation();
				$(this).closest(".content-column").remove();
				formSetting.renderLayoutSettingPanel();
			}).on("click", ".remove-draggable-element", function(evt) {
				//删除元素
				evt.stopPropagation();
				let dragElement = $(this).closest(".draggable-element");
				let tmpInstance = dragElement.data("componentInstance");
				if(tmpInstance) {
					tmpInstance.shown(false);
				}
				dragElement.remove();
				formSetting.renderPanel();
			}).on("click", ".draggable-element", function(evt) {
				//console.log("元素设置");
				//console.log(this);
				evt.stopPropagation();
				var ths = $(this);
				//切换表单设置面板中的内容
				if(ths.hasClass("active")) {
					return true;
				}
				/*$("#layout-main .content-column.active").removeClass("active");
				$("#layout-main .draggable-element.active").removeClass("active");*/
				$("#layout-main .ui-draggable.active").removeClass("active");
				ths.addClass("active");
				/*let tmpInstance = ths.data('componentInstance');
				if(tmpInstance) {
					console.log(tmpInstance);
					let settins = tmpInstance.formSets();
					console.log(settins);
					let setli = $("#form-setting");
					setli.empty();
					for( let i in settins ) {
						let si = settins[i];
						si.render(setli, tmpInstance);//调用设置项上定义的渲染方法
					}
				}*/
				formSetting.renderPanel();
			}).on("click", ".content-column", function(evt) {
				console.log("布局设置");
				console.log(this);
				var ths = $(this);
				//切换表单设置面板中的内容
				if(ths.hasClass("active")) {
					return true;
				}
				$("#layout-main .ui-draggable.active").removeClass("active");
				ths.addClass("active");
				formSetting.renderLayoutSettingPanel();
			});
		}
	}

	let _initElementDrag = () => {
		//左侧控件列表中的控件元素，初始化拖拽
		$("#layout-left .draggable-element").draggable({
			appendTo: document.body,
			cursorAt: { op: 0, left: 0 },
			connectToSortable: "#layout-main .drag-form-lay",
			helper: "clone",
			drag: function(e, t) {
				t.helper.css("z-index", 10000);
			},
			stop: function(e, t) {
				try{
					layoutElementDragOver(t.helper);
				}catch(e){
					console.log(e);
				}
			}
		});
	}

	let _initDrag = () => {
		$("#layout-main").sortable({
			appendTo: document.body,
			connectWith: "#layout-main .content-column",
			opacity: .35,
			handle: ".drag",
			/*helper: "clone"*/
			stop: function(e, t) {
				t.item?.removeAttr("style");
			}
		});

		$("#layout-main .drag-form-lay").sortable({
			appendTo: document.body,
			opacity: .35,
			connectWith: ".draggable-element",
			stop: function(e, t) {
				t.item?.removeAttr("style");
			}
		});
		
		//拖拽布局
		$("#layout-left .content-column").draggable({
			appendTo: document.body,
			cursorAt: { top: 0, left: 0 },
			connectToSortable: "#layout-main",
			helper: "clone",
			drag: function(e, t) {
			},
			stop: function(e, t) {
				layoutWrapperDragOver(t.helper);
				$("#layout-main .drag-form-lay").sortable({
					appendTo: document.body,
					opacity: .35,
					connectWith: "#layout-main .content-column"
				});
				
				_initElementDrag();
			}
		});
		
		_initElementDrag();
	}


	/**
	 * 初始化事件绑定
	 */
	let _initDragFormClick = () => {
		/**
		 * 点击表单元素，更新“表单设置”面板中的内容
		 */
		let dragFormWorkarea = $("#layout-main");
		dragFormWorkarea.on("click", ".draggable-element", () => {
			
			
			return true;
		});
	}
	
	return {
		init: function() {
			console.log("初始化拖拽功能");
			_initCommon();
			_initDrag();
			_initDragFormClick();
		},
		_initCommon: function() {

		},
		_initDrag: function() {

		}
	}
});